# user: oshrishm		id: 066583485

# Exercise 4 Question 4 - implementaion of ispalindrome

	.data	
msg:	.asciiz "\nThe string is "
pal:	.asciiz "a palindrome\n"
notStr:	.asciiz "not "
	.text
	.globl main
main:	
	# allocate 31 bytes
	li $v0, 9
	li $a0, 31
	syscall
	
	move $s0, $v0
	move $a0, $s0
	
	# read string from user
	li $v0, 8
	li $a1, 30
	syscall
	
	# null-terminate the string read from the user
	move $a0, $s0
	jal str_fixer
	
	jal ispalindrome
	move $s0, $v0
	
	li $v0, 4
	la $a0, msg
	syscall
	bne $s0, $zero, print_pal
	la $a0, notStr
	syscall	
print_pal:
	la $a0, pal
	syscall
	
	li $v0, 10		# exits program
	syscall

# this function recieves a string read from the user and replaces the \n in it's end with a null
str_fixer:
	# save anything we are going to use
	addi $sp, $sp, -8
	sw $s0, 0($sp)
	sw $s1, 4($sp)
	
	li $s1, 10			# $s1 is the constant ascii value of newline
	
# while we havent reached the null termination of the string keep on reading
	move $s0, $zero				# i = 0
loop: 
	add $t0, $a0, $s0			# string_address + i
	lb $t1, 0($t0)				# *(string_address + i)
	beq $t1, $zero, exit_str_fixer
	beq $t1, $s1, fixer			# if the byte being checked is '\n' fix it
	addi $s0, $s0, 1			# i++
	j loop
	
# replace the current byte with null == 0
fixer:
	sb $zero, 0($t0)
	j exit_str_fixer
	
# return everthing to it's place
exit_str_fixer:
	lw $s0, 0($sp)
	lw $s1, 4($sp)
	addi $sp, 8
	jr $ra
	
# ispalindrome: the function recieves a string address and checks if it a ispalindrome
# explenation: the function sets two pointers, one to the head and another to the tail of the string
# 		then compares pairs of chars to see wether they are the same
#		while moving forward with the head pointer, and backwards with the tail pointer
#		until the head passed the tail or is with it on the same byte (address-wise)
ispalindrome:
	# save stuff the function uses
	addi $sp, $sp, -20
	sw $s0, 0($sp)
	sw $s1, 4($sp)
	sw $s2, 8($sp)
	sw $s3, 12($sp)
	sw $s4, 16,($sp)

	add $s0, $a0, $zero
	move $s1, $s0
	
# loop over the string till the null-termination
pal_loop:
	lb $s2, 1($s1)
	beq $s2, $zero, end_loop
	addi $s1, $s1, 1
	j pal_loop
end_loop:
pal_loop2:
	sge $v0, $s0, $s1			# set $v0 to be 1 iff we checked the whole word or if it has only one char
	bne $v0, $zero, exit_ispalindrome	# if $v0 if not 0 => it is 1 so the word is a palindrome
	lb $s3, 0($s0)				# load the left char
	lb $s4, 0($s1)				# load the right char
	bne $s3, $s4, exit_ispalindrome		# if the chars are not the same then this is not a palindrome
	addi $s0, $s0, 1			# advance a char with $s0
	addi $s1, $s1, -1			# go back a char with $s1
	j pal_loop2
exit_ispalindrome:
	# clean-up
	lw $s0, 0($sp)
	lw $s1, 4($sp)
	lw $s2, 8($sp)
	lw $s3, 12($sp)
	lw $s4, 16,($sp)
	addi $sp, $sp, 20
	jr $ra
	
# END OF PROGRAM